/**
 * 支付通知接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

//storePay接口入口文件
let index = function(getData, postData, config, _redis, _db) {
	let deferred = Q.defer();
	try {
		if(postData.xml) {
			let payResultData = postData.xml;
			for(let key in payResultData) {
				payResultData[key] = payResultData[key][0] || payResultData[key];
			}
			console.log(payResultData);
			util.checkWxData(payResultData, config.payKey).then(function(result) {
				if(result) {
					console.log('支付消息确认来自微信服务器');
					let {
						//APPID
						appid,
						//订单出处
						attach,
						//银行类型
						bank_type,
						//是否关注小程序
						is_subscribe,
						//商户号
						mch_id,
						//随机字符串
						nonce_str,
						//支付的用户
						openid,
						//商户的订单号
						out_trade_no,
						//结果代码
						result_code,
						//返回代码
						return_code,
						//订单结束时的时间戳
						time_end,
						//订单总金额
						total_fee,
						//微信支付订单号
						transaction_id
					} = payResultData;
					let orderId = out_trade_no;
					let storeId = orderId.split('-')[0];
					if(return_code == 'SUCCESS' && result_code == 'SUCCESS' && storeId && storeId != '') {
						let db;
						_db.connectDB(storeId).then(function(storeDB) {
							db = storeDB;
							return db.select('storeOrder', {
								userId: payResultData.openid,
								orderId: payResultData.out_trade_no
							});
						}).then(function(orderData) {
							console.log(orderData);
							if(orderData[0] && orderData[0].storeId) {
								orderData = orderData[0];
								let orderTotal = 0;
								for(var foodIndex in orderData.goodsList) {
									let price = orderData.goodsList[foodIndex].foodPrice || orderData.goodsList[foodIndex].goodsPrice;
									let count = orderData.goodsList[foodIndex].count || orderData.goodsList[foodIndex].goodsCount;
									orderTotal += parseInt(price) * parseInt(count);
								}
								db.update('storeOrder', {
									orderId: payResultData.out_trade_no
								}, {
									userPayed: true
								}).then(function() {
									console.log('已成功将' + payResultData.out_trade_no + '这个订单的状态设置为用户已支付');
									let notifyPayDoneFun = function(userData) {
										orderData._id = undefined;
										orderData.userPayed = true;
										orderData.userData = userData;
										deferred.resolve(['echo', '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>', 'broadcast', {
											storeId: storeId,
											type: 'sys',
											event: 'orderPayDone',
											data: orderData
										}]);
									}
									_db.connectDB('common').then(function(commonDB) {
										return commonDB.select('users', {userId: orderData.userId});
									}, function() {
										notifyPayDoneFun();
									}).then(function(userData) {
										userData = userData[0] ? userData[0] : {}
										notifyPayDoneFun(userData);
									}, function() {
										notifyPayDoneFun();
									});
								}, function() {
									console.log('错误！无法将' + payResultData.out_trade_no + '这个订单的状态设置为用户已支付');
									db.insert('errorOrder', payResultData);
									deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[更新商户订单状态失败]]></return_msg></xml>']);
								});
							}
							else {
								deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单数据错误，可能不存在此订单]]></return_msg></xml>']);
								return deferred.promise;
							}
						}, function() {
							deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[查询订单失败]]></return_msg></xml>']);
						});
					}
				}
				else {
					console.log('支付消息不是来自微信服务器');
					deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>']);
				}
			}, function() {
				console.log('校验支付通知失败');
				deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>']);
			});
		}
		else {
			console.log('支付通知参数格式错误');
			deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[参数格式校验错误]]></return_msg></xml>']);
		}
	}
	catch(e) {
		console.log('支付通知处理时出现错误', e);
		deferred.resolve(['echo', '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理时出现错误]]></return_msg></xml>']);
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
}